package com.twu.biblioteca.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Enrico on 16/09/2014.
 */
public class MyFileReader {

    public static List<String> read(String filename) {
        String path = getFile(filename);

        BufferedReader reader = null;
        List<String> itemList = new ArrayList<String>();
        try {
            reader = new BufferedReader(new java.io.FileReader(path));

            String line;

            while ((line = reader.readLine()) != null) {
                //add lines to List
                itemList.add(line);
            }
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException io) {
                io.printStackTrace();
            }
        }
        return itemList;
    }

    public static String getFile(String filename) {
        if (filename == null) throw new NullPointerException("The file name cannot be null");

        String workingDir = System.getProperty("user.dir");
        String path = workingDir + "/resources/" + filename;

        File file = new File(path);

        if(!file.exists() || file.isDirectory()) throw new IllegalArgumentException("The file does not exist");

        return file.getAbsolutePath();
    }
}
